<?php

/*
 * To change this template, choose Tools | Templates and open the template in the editor.
 */

/**
 * Description of ImageController
 *
 * @author KOI
 */
class ImageController extends FrontEndController {

    public function filters() {
        return array(
            'accessControl',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', 'actions' => array('upload', 'like', 'comment', 'addtags', 'edittag', 'removetag'),
                'roles' => array('member')
            ),
            array('allow', 'actions' => array('view'),
                'users' => array('*')
            ),
            array('deny', 'users' => array('*')
            )
        );
    }

    public function actionDelete($id) {
        $image = $this->loadImage($id);
        if ($image != null && $image->user_created == Yii::app()->user->id) {
            $image->delete();
        } else {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }

    public function actionUpload() {
        $model = new Image ('upload');
        if (isset($_POST ['Image'])) {
            $model->attributes = $_POST ['Image'];
            $uploadedFile = CUploadedFile::getInstance($model, 'img_url');
            $fileName = md5(date("Y-m-d H:i:s") . $model->userCreated . $uploadedFile) . '.' . $uploadedFile->extensionName;
            $model->user_created = Yii::app()->user->id;
            $model->created_at = date("Y-m-d H:i:s");
            $model->img_url = $fileName;
            $model->title = CHtml::encode($model->title);
            if ($model->save()) {
                $imageFollow = new ImageUserFollow ();
                $imageFollow->image_id = $model->id;
                $imageFollow->user_id = Yii::app()->user->id;
                $imageFollow->follow_at = date("Y-m-d H:i:s");
                $imageFollow->save();

                $userActive = new UserActive ();
                $userActive->active_type = UserActive::UPLOAD_IMG;
                $userActive->active_at = date('Y-m-d H:i:s');
                $userActive->image_id = $model->id;
                $userActive->user_id = Yii::app()->user->id;
                $userActive->save();

                $uploadedFile->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images/' . $fileName);
                $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images/' . $fileName);
                $image->quality(40);
                $image->save(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images/small-' . $fileName);

                Yii::import('ext.facebook.Facebook');

                $facebook = new Facebook(array(
                    'appId' => '128317560709307',
                    'secret' => 'feb508a994e8f14286f48b74efff5291'
                ));
                $userId = $facebook->getUser();
                if ($userId) {
                    $facebook->setFileUploadSupport(true);
                    $result = $facebook->api('/me?fields=albums.fields(id,name)');
                    $album_uid = NULL;
                    $album_list = $result['albums']['data'];
                    for ($index = 0; $index < count($album_list); $index++) {
                        $album = $album_list[$index];
                        if ($album['name'] == 'Fchic') {
                            $album_uid = $album['id'];
                            break;
                        }
                    }
                    if ($album_uid == NULL) {
                        $album_details = array(
                            'message' => $model->created_at,
                            'name' => 'Fchic'
                        );
                        $create_album = $facebook->api('/me/albums', 'post', $album_details);
                        $album_uid = $create_album['id'];
                    }
                    $photo_details = array(
                        'message' => $model->title
                    );

                    $photo_details['image'] = '@' . realpath(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images/' . $fileName);
                    $upload_photo = $facebook->api('/' . $album_uid . '/photos', 'post', $photo_details);
                }

                $this->redirect(Yii::app()->homeUrl);
            }
        }

        $this->render('upload', array(
            'model' => $model
        ));
    }

    public function actionView($id) {
        if (!Yii::app()->user->isGuest) {
            $user = $this->loadUser(Yii::app()->user->id);
            $style = $user->style;
            if (!is_null($style) && sizeof($style) > 0) {
                $list = array();
                foreach ($style as $value) {
                    $list [] = $value->style_id;
                }
                $lists = implode(",", $list);
                $styles = "s.style_id in ($lists)";
            } else {
                $styles = "1=1";
            }
            $userfollow = UserFollow::model()->findAll('follower=:id', array(':id' => Yii::app()->user->id));
            if ($userfollow && sizeof($userfollow) > 0) {
                $list = array();
                foreach ($userfollow as $u) {
                    $list [] = $u->followed;
                }
                $lists = implode(",", $list);
                $usersf = "u.id not in ($lists)";
            } else {
                $usersf = "1=1";
            }
            $sql = "Select u.id From tbl_user u left join tbl_image img on u.id = img.user_created left join tbl_user_style s on u.id = s.user_id Where u.id <>:id and " . $usersf . "  and " . $styles . " GROUP BY u.id Order BY SUM(img.like_cnt) DESC LIMIT 0,10";
            $users = User::model()->findAllBySql($sql, array(':id' => Yii::app()->user->id));
            if (!is_null($users) && sizeof($users) > 0) {
                $list = array();
                unset($user);
                foreach ($users as $user) {
                    $list [] = $user->id;
                }
                $users = User::model()->findAll("id in (" . implode(",", $list) . ")", array());
            } else {
                $users = null;
            }
        } else {

            $users = null;
        }
        $model = Image::model()->find('id=:id and status = :status', array(':id' => $id, ':status' => Image::IMAGE_ACTIVE));
        $sql = 'SELECT ci.* FROM tbl_collection_image ci join tbl_collection c on ci.collection_id = c.id where ci.image_id =:image_id and c.user_created =:user';
        $imageInCollection = CollectionImage::model()->findBySql($sql, array(':image_id' => $id, ':user' => $model->user_created));
        $sameImages = null;
        if ($imageInCollection) {
            $sql = 'SELECT i.* FROM tbl_image i join tbl_collection_image ci on ci.image_id = i.id where ci.collection_id =:collection_id and i.status =:status and i.id<>:id';
            $sameImages = Image::model()->findAllBySql($sql, array(':collection_id' => $imageInCollection->collection_id, ':status' => Image::IMAGE_ACTIVE, ':id' => $id));
        }
        $allComment = Comment::model()->findAll('image_id=:image_id and status = :status order by comment_at DESC limit 0,5', array(':image_id' => $id, ':status' => Comment::COMMENT_ACTIVE));
        $tags = ImageTag::model()->findAll('image_id=:image_id and status = :status', array(':image_id' => $id, ':status' => ImageTag::TAG_ACTIVE));
        if (!empty($_SERVER ['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER ['HTTP_CLIENT_IP'];
            // Is it a proxy address
        } elseif (!empty($_SERVER ['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER ['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER ['REMOTE_ADDR'];
        }
        if (Yii::app()->user->isGuest) {
            $check = ImageView::model()->find('image_id=:id and ip =:ip and view_at >DATE_SUB(NOW(), INTERVAL 1 DAY)', array(
                ':id' => $id,
                ':ip' => $ip
            ));
            if (!$check) {
                $imageView = new ImageView ();
                $imageView->image_id = $model->id;
                $imageView->view_at = date("Y-m-d H:i:s");
                $imageView->ip = $ip;
                $imageView->insert();
                $model->view_cnt = $model->view_cnt + 1;
                $model->update();
            }
        } else {
            $check = ImageView::model()->find('image_id=:id and user_id =:user_id and view_at >DATE_SUB(NOW(), INTERVAL 1 DAY)', array(
                ':id' => $id,
                ':user_id' => Yii::app()->user->id
            ));
            if (!$check) {
                $imageView = new ImageView ();
                $imageView->image_id = $model->id;
                $imageView->view_at = date("Y-m-d H:i:s");
                $imageView->user_id = Yii::app()->user->id;
                $imageView->insert();
                $model->view_cnt = $model->view_cnt + 1;
                $model->update();
            }
        }
        $comment = new Comment ();
        $this->render('view', array(
            'comment' => $comment,
            'model' => $model,
            'sameImages' => $sameImages,
            'tags' => $tags,
            'allComment' => $allComment,
            'imageInCollection' => $imageInCollection,
            'users' => $users
        ));
    }

    public function actionComment($id) {
        $comment = new Comment ();
        if (isset($_POST ['Comment'])) {
            $comment->attributes = $_POST ['Comment'];
            $comment->comment_at = date("Y-m-d H:i:s");
            $comment->user_id = Yii::app()->user->id;
            $comment->image_id = $_GET ['id'];
            $comment->content = CHtml::encode($comment->content);
            if ($comment->save()) {
                $check = ImageUserFollow::model()->find("user_id = :user_id and image_id =:image_id", array(
                    ':image_id' => $_GET ['id'],
                    'user_id' => Yii::app()->user->id
                ));
                if (!$check) {
                    $imageFollow = new ImageUserFollow ();
                    $imageFollow->image_id = $_GET ['id'];
                    $imageFollow->user_id = Yii::app()->user->id;
                    $imageFollow->follow_at = date("Y-m-d H:i:s");
                    $imageFollow->save();
                }

                $userActive = new UserActive ();
                $userActive->active_type = UserActive::COMMENT_IMG;
                $userActive->active_at = date('Y-m-d H:i:s');
                $userActive->image_id = $_GET ['id'];
                $userActive->user_id = Yii::app()->user->id;
                $userActive->save();

                $this->redirect(array(
                    'view',
                    'id' => $id
                ));
            }
        }
        $this->redirect(array(
            'view',
            'id' => $id
        ));
    }

    public function actionAddtags($id) {
        $model = Image::model()->find('id=:id and status = :status', array(':id' => $id, ':status' => Image::IMAGE_ACTIVE));
        if (!$model)
            throw new CHttpException(404, 'The requested page does not exist.');
        if ($model->user_created == Yii::app()->user->id) {
            $tag = new ImageTag();
            $tag->image_id = $id;
            if (isset($_POST ['ImageTag'])) {
                $tag->attributes = $_POST ['ImageTag'];
                if ($tag->validate()) {
                    if ($tag->insert())
                        $this->redirect(array('view', 'id' => $id));
                }
            }
            $this->render('addtags', array('tag' => $tag));
        } else {
            throw new CHttpException(403, 'You are not authorized to perform this action.');
        }
    }

    public function actionEdittag($id) {
        $tag = ImageTag::model()->findByPk($id);
        if (!$tag || $tag->status != ImageTag::TAG_ACTIVE) {
            throw new CHttpException(404, 'The requested page does not exist.');
        } else {
            if ($tag->image->user_created != Yii::app()->user->id) {
                throw new CHttpException(403, 'You are not authorized to perform this action.');
            } else {
                if (isset($_POST ['ImageTag'])) {
                    $tag->attributes = $_POST ['ImageTag'];
                    if ($tag->validate()) {
                        if ($tag->save())
                            $this->redirect(array('view', 'id' => $tag->image->id));
                    }
                }
                $this->render('edittag', array('tag' => $tag));
            }
        }
    }

    public function actionRemovetag($id) {
        $tag = ImageTag::model()->findByPk($id);
        if (!$tag || $tag->status != ImageTag::TAG_ACTIVE) {
            throw new CHttpException(404, 'The requested page does not exist.');
        } else {
            if ($tag->image->user_created != Yii::app()->user->id) {
                throw new CHttpException(403, 'You are not authorized to perform this action.');
            } else {
                $id = $tag->image->id;
                $tag->delete();
                $this->redirect(array('view', 'id' => $id));
            }
        }
    }

    public function actionLike($id) {
        $result = array();
        $image = $this->loadImage($id);
        $check = ImageLike::model()->find("user_id = :user_id and image_id =:image_id", array(
            ':image_id' => $id,
            'user_id' => Yii::app()->user->id
        ));
        if ($check) {
            $check->delete();
            $image->like_cnt = $image->like_cnt - 1;
            $image->update();
            $result ['meg'] = 'Thích';
        } else {
            $model = new ImageLike ();
            $model->image_id = $id;
            $model->user_id = Yii::app()->user->id;
            if ($model->insert()) {
                $userActive = new UserActive ();
                $userActive->user_id = Yii::app()->user->id;
                $userActive->image_id = $id;
                $userActive->active_at = date('Y-m-d H:i:s');
                $userActive->active_type = UserActive::LIKE_IMG;
                $userActive->insert();
            }
            $image->like_cnt = $image->like_cnt + 1;
            $image->update();
            $result ['meg'] = 'Bỏ thích';
        }

        $result ['like_cnt'] = $image->like_cnt;

        echo json_encode($result);
    }

    public function loadImage($id) {
        $model = Image::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function loadUser($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

}

?>
